package net.dopan.pigframe.config.annotation;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * 功能描述:清除缓存切面类
 *
 * @author fuyuchao
 * DATE 2018/9/14.
 */
@Component
@Aspect
@Slf4j
public class CacheRemoveAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    //截获标有@CacheRemove的方法
//    @Pointcut(value = "@annotation(net.dopan.pigframe.config.annotation.CacheRemove))")
//    private void pointcut() {
//    }

    /**
     * 功能描述: 切面在截获方法返回值之后
     *
     * @return void
     * @throws
     * @author fuyuchao
     * @date 2018/9/14 16:55
     * @params [joinPoint]
     */
    /**
     * 使用空方法定义切点表达式
     */
//    @Around(value = "execution(* net.dopan.pigframe.demo.service.impl.UserConcernUserServiceImpl.*(..))")
   @Around("@annotation(net.dopan.pigframe.config.annotation.CacheRemove)")
    public void execute(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取被代理的类
        Object target = joinPoint.getTarget();
        Object[] args = joinPoint.getArgs(); // 参数值
        //获取切入方法的数据
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
       for (Object obj:args
            ) {
           System.err.println(obj+"==================================================");
       }
        //获取切入方法
        Method method = signature.getMethod();
        //获得注解
        CacheRemove cacheRemove = method.getAnnotation(CacheRemove.class);

        if (cacheRemove != null) {
            //清除当前类的缓存
            cleanRedisCache("*" + target.getClass().toString() + "*");

            String value = cacheRemove.value();
            if (!value.equals("")) {
                //缓存的项目所有redis业务部缓存
                cleanRedisCache("*" + value + "*");
            }
            //需要移除的正则key
            System.err.println(cacheRemove.key());
            String[] keys = cacheRemove.key();
            for (String key : keys) {
                System.err.println(key);
                cleanRedisCache("*" + key + "*");
            }
        }
    }

    private void cleanRedisCache(String key) {
        if (key != null) {
            Set<String> stringSet = redisTemplate.keys(key);
            redisTemplate.delete(stringSet);//删除缓存
            log.info("清除 " + key + " 缓存");
        }
    }
}
